package com.project.controller.web;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.project.common.utils.ShiroUtils;
import com.project.entity.User;
import org.apache.commons.io.IOUtils;
import com.project.myBeans.ConfigParameters;
import com.project.myBeans.LoginInfo;
import com.project.myBeans.R;
import com.project.service.UserService;
import com.project.service.base.BaseService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author: TateBrown
 * @date: 2018/5/25 22:25
 * @param:
 * @return:
 */
@Api(description="登录退出接口")
@Controller
public class LoginController extends BaseService {
    @Autowired
    UserService userService;

    @Autowired
    private Producer producer;

    @Autowired
    private ConfigParameters configParameters;
    @ApiOperation("用户登录")
    @RequestMapping(value = "/toLogin", method = RequestMethod.POST)
    @ResponseBody
    public R login(@RequestBody LoginInfo loginInfo, HttpServletRequest request){
          log.info("login>>>>>>>>>>>>>>>>>");

          try{
              String msg,token;
              Long expirationTime;
              String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
              if(kaptcha==null){
                  return R.error("验证码已失效");
              }
              if(!loginInfo.getCaptcha().equalsIgnoreCase(kaptcha)){
                  return R.error("验证码不正确");
              }


              //用户是否登陆
              Subject subject = SecurityUtils.getSubject();//get current user
              Session session =subject.getSession();
              User user =userService.findOneByUserNameAndUniversityId(loginInfo.getUsername(),loginInfo.getUniversityid());
              if(subject.isAuthenticated()){
                  return R.error("请勿重复登陆");
              }
              if(user==null){
                  if(loginInfo.getUniversityid()==null) {
                      return R.error("请选择学校");
                  }
                  return R.error("用户名或密码错误");
              }

              //用户没有登陆，跳转到登陆页面
              if(!subject.isAuthenticated()){
                  if(!userLogin(subject,request,loginInfo.getUsername(),loginInfo.getPassword())){
                      return R.error("登陆失败");
                  }
              }

              //若执行到底仍没有结束，那么表示用户名和密码都是正确.
              //开始获取用户的菜单
              session.setAttribute("currentUser",user);
              int userType=user.getUsertype();


              //设置token
              DateTime dt=new DateTime();
              String key=configParameters.getJwtSecret();
              expirationTime=System.currentTimeMillis()+configParameters.getJwtExpire()*1000;//ms

              token= Jwts.builder()                //创建token
                      .setIssuer(user.getId().toString())
                      .setExpiration(dt.plusSeconds(configParameters.getJwtExpire()).toDate())
                      .signWith(SignatureAlgorithm.HS512, key)
                      .compact();

              Map<String,Object> userInfo=new HashMap<>();
              userInfo.put("id",user.getId());
              userInfo.put("username",user.getUsername());
              userInfo.put("usertype",user.getUsertype());
              userInfo.put("state",user.getState());

              return R.ok("登陆成功").put("token",token).put("expire",expirationTime).put("user",userInfo);
          }catch (Exception e){
              e.printStackTrace();
              return R.error("登陆失败，请刷新重试");
          }
    }

    @ApiOperation("验证码")
    @RequestMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response) throws ServletException,IOException {
        response.setHeader("Cache-Control", "no-store,nocache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * author: TateBrown
     * date: 05/26/2018
     *
     * @param request
     * @return
     */
    @ApiOperation("退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Object Logout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();

        if (subject.isAuthenticated()) {
            session.stop();
            subject.logout();
            session = subject.getSession();
        }
        return "login";
    }

}
